﻿using System;
using System.Linq;
using WI.CandidateManager.Business.Objects.Helper;
using WI.CandidateManager.Common.Data.Entities;
using WI.CandidateManager.Common.Data.Enums;

namespace WI.CandidateManager.Business.Objects
{
    /// <summary>
    /// Logic for loggin process of User
    /// </summary>
    public class LoginBO : BOBase
    {
        /// <summary>
        /// Login user
        /// </summary>
        /// <param name="login">login of user</param>
        /// <param name="password">password of user</param>
        /// <returns>role if user-pass is exist and correct and throw exeptions if nouser was found, incorrect password
        /// or one more user was found</returns>
        /// Remark: LoginController must have try-catch block.
        public UserRole Login(string login, string password)
        {
            UserBase user;

            try
            {
                user = this.DataContext.UserBaseSet
                    .Single(u => u.Login == login);

                Logger.Info(String.Format("User {0} is found in DB", login));

                CryptoHelper cryptedPassword = new CryptoHelper(user.Password);

                if (cryptedPassword.Verify(password))
                {
                    Session.User = user;
                    Logger.Info(String.Format("User {0} is authorized", login));
                    return user.Role;
                }
                else
                {
                    Logger.Info(String.Format("User {0} is not authorized", login));
                    return UserRole.Anonymous;
                }
            }
            catch (Exception ex)
            {
                Logger.Error(String.Format("Unable to login with a login ({0})", login), ex);
                throw new InvalidOperationException(String.Format("Unable to login with a login ({0})", login), ex);
            }
        }
    }
}
